package wang.naifei.core.spring.mvc.rest;/*
 * <h3>Title:wheel-parent系统</h3>
 * <p>Copyright (c) 2022, wnfbx@163.com. All rights reserved.</p>
 * @author wnfbx@163.com
 */

import org.springframework.core.io.AbstractResource;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * <dt>Description:SimpleMultipartFileResource</dt>
 * <dd>实现MultipartFileResource的作用</dd>
 * <dd>copy from org.springframework.web.multipart.MultipartFileResource</dd>
 *
 * @author wnfbx@163.com
 * @version 1.0 <i>2022/5/30 17:18</i>
 * @since jdk1.7+
 */
public class SimpleMultipartFileResource extends AbstractResource {

    private final MultipartFile multipartFile;

    public SimpleMultipartFileResource(MultipartFile multipartFile) {
        Assert.notNull(multipartFile, "MultipartFile must not be null");
        this.multipartFile = multipartFile;
    }

    /**
     * This implementation always returns {@code true}.
     */
    @Override
    public boolean exists() {
        return true;
    }

    /**
     * This implementation always returns {@code true}.
     */
    @Override
    public boolean isOpen() {
        return true;
    }

    @Override
    public long contentLength() {
        return this.multipartFile.getSize();
    }

    @Override
    public String getFilename() {
        return this.multipartFile.getOriginalFilename();
    }

    /**
     * This implementation throws IllegalStateException if attempting to
     * read the underlying stream multiple times.
     */
    @Override
    public InputStream getInputStream() throws IOException, IllegalStateException {
        return this.multipartFile.getInputStream();
    }

    /**
     * This implementation returns a description that has the Multipart name.
     */
    @Override
    public String getDescription() {
        return "MultipartFile resource [" + this.multipartFile.getName() + "]";
    }


    @Override
    public boolean equals(Object other) {
        return (this == other || (other instanceof SimpleMultipartFileResource &&
                ((SimpleMultipartFileResource) other).multipartFile.equals(this.multipartFile)));
    }

    @Override
    public int hashCode() {
        return this.multipartFile.hashCode();
    }
}
